// 获取URL参数
function getQueryParam(name) {
	const urlParams = new URLSearchParams(window.location.search);
	return urlParams.get(name);
}

// 加载商品数据
function loadGoods(page = 1) {
	const catId = getQueryParam('catId') || '';
	const pageSize = 10;

	// 模拟数据 - 实际使用时应替换为ajax请求
	const mockData = {
		data: Array(10).fill().map((_, i) => ({
			goods_id: i + 1,
			goods_thumb: `img/product${i + 1}.jpg`,
			goods_name: `商品${i + 1}`
		})),
		total: 50 // 假设总共50条数据
	};

	// 实际使用时替换为：
	// ajax({
	//     url: BASE_URL + `/api_goods?page=${page}&pagesize=${pageSize}${catId ? '&catId='+catId : ''}`,
	//     method: "get",
	//     callback: function(data) {
	//         renderGoods(data.data);
	//         renderPagination(page, Math.ceil(data.total/pageSize), catId);
	//     }
	// });

	renderGoods(mockData.data);
	renderPagination(page, Math.ceil(mockData.total / pageSize), catId);
}

// 渲染商品列表
function renderGoods(goodsList) {
	let html = '';

	if (goodsList.length === 0) {
		html = '<div class="no-goods">暂无商品数据</div>';
	} else {
		// 第一行：左边大图，右边四个小图
		html += '<div class="good_list_row">';
		if (goodsList[0]) {
			html += `
                        <div class="good_list_big">
                            <a href="goodinfo.html?goods_id=${goodsList[0].goods_id}">
                                <img src="${goodsList[0].goods_thumb}" alt="${goodsList[0].goods_name}" />
                            </a>
                        </div>
                    `;
		}

		html += '<div class="good_list_small_container">';
		for (let i = 1; i <= 4; i++) {
			if (goodsList[i]) {
				html += `
                            <div class="good_list_small">
                                <a href="goodinfo.html?goods_id=${goodsList[i].goods_id}">
                                    <img src="${goodsList[i].goods_thumb}" alt="${goodsList[i].goods_name}" />
                                </a>
                            </div>
                        `;
			}
		}
		html += '</div></div>';

		// 第二行：左边四个小图，右边大图
		html += '<div class="good_list_row reverse">';
		html += '<div class="good_list_small_container">';
		for (let i = 5; i <= 8; i++) {
			if (goodsList[i]) {
				html += `
                            <div class="good_list_small">
                                <a href="goodinfo.html?goods_id=${goodsList[i].goods_id}">
                                    <img src="${goodsList[i].goods_thumb}" alt="${goodsList[i].goods_name}" />
                                </a>
                            </div>
                        `;
			}
		}
		html += '</div>';

		if (goodsList[9]) {
			html += `
                        <div class="good_list_big">
                            <a href="goodinfo.html?goods_id=${goodsList[9].goods_id}">
                                <img src="${goodsList[9].goods_thumb}" alt="${goodsList[9].goods_name}" />
                            </a>
                        </div>
                    `;
		}
		html += '</div>';
	}

	document.querySelector('.good_list_top').innerHTML = html;
}

// 渲染分页
function renderPagination(currentPage, totalPages, catId) {
	let paginationHtml = '';
	const maxVisiblePages = 5; // 最多显示5个页码

	// 上一页按钮
	paginationHtml += `<a href="#" class="page-link ${currentPage === 1 ? 'disabled' : ''}" 
                data-page="${currentPage - 1}">上一页</a>`;

	// 计算显示的页码范围
	let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
	let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

	if (endPage - startPage + 1 < maxVisiblePages) {
		startPage = Math.max(1, endPage - maxVisiblePages + 1);
	}

	// 第一页
	if (startPage > 1) {
		paginationHtml += `<a href="#" class="page-link" data-page="1">1</a>`;
		if (startPage > 2) {
			paginationHtml += `<span class="ellipsis">...</span>`;
		}
	}

	// 中间页码
	for (let i = startPage; i <= endPage; i++) {
		paginationHtml += currentPage === i ?
			`<span class="current-page">${i}</span>` :
			`<a href="#" class="page-link" data-page="${i}">${i}</a>`;
	}

	// 最后一页
	if (endPage < totalPages) {
		if (endPage < totalPages - 1) {
			paginationHtml += `<span class="ellipsis">...</span>`;
		}
		paginationHtml += `<a href="#" class="page-link" data-page="${totalPages}">${totalPages}</a>`;
	}

	// 下一页按钮
	paginationHtml += `<a href="#" class="page-link ${currentPage === totalPages ? 'disabled' : ''}" 
                data-page="${currentPage + 1}">下一页</a>`;

	document.querySelector('.pagination').innerHTML = paginationHtml;

	// 绑定分页点击事件
	document.querySelectorAll('.page-link').forEach(link => {
		link.addEventListener('click', function(e) {
			e.preventDefault();
			const page = parseInt(this.dataset.page);
			if (page >= 1 && page <= totalPages) {
				window.location.href = `goodlist.html?page=${page}${catId ? '&catId='+catId : ''}`;
			}
		});
	});
}

window.onload = function() {
	// 加载商品分类导航
	getGoodNavType((data) => {
		let typeList = document.querySelector(".type_list>ul");
		let goodListData = data.data;
		let text = '';
		goodListData.forEach((item, index) => {
			text +=
				`<li><a href="goodlist.html?catId=${item.cat_id}"><img src="${item.cat_img}" alt=""/><p>${item.cat_name}</p></a></li>`;
		});
		typeList.innerHTML = text;
	});

	// 初始加载商品数据
	let currentPage = parseInt(getQueryParam('page')) || 1;
	loadGoods(currentPage);

	// 搜索功能
	const searchInput = document.getElementById('searchInput');
	const searchBtn = document.getElementById('searchBtn');

	searchBtn.addEventListener('click', function() {
		const keyword = searchInput.value.trim();
		if (keyword) {
			window.location.href = 'search.html?keywords=' + encodeURIComponent(keyword);
		}
	});

	searchInput.addEventListener('keypress', function(e) {
		if (e.key === 'Enter') {
			const keyword = searchInput.value.trim();
			if (keyword) {
				window.location.href = 'search.html?keywords=' + encodeURIComponent(keyword);
			}
		}
	});
}